<?php
require_once 'Zend/Controller/Plugin/Abstract.php';

/**
 * 文件上传插件
 * 
 * Zend Framework 专用
 * 
 * @example
 * 
 * 在控制器中执行
 * $upload = new Custom_Controller_Plugin_Upload();
   $upload->Upload($_FILES, $this->view->baseUrl());
 * 
 * @author 高强
 */
class Custom_Controller_Plugin_Upload extends Zend_Controller_Plugin_Abstract
{
	
	public function Upload($files, $baseUrl)
	{
		$adapter = new Zend_File_Transfer_Adapter_Http();
		
		$detination = $_SERVER['DOCUMENT_ROOT'].$baseUrl. '/upload/tmpfiles/';
		$adapter->setDestination($detination);
		
		// 上传过滤条件
		$adapter->addValidator('Extension', false, 'png,jpg,gif,doc,xls,pdf,txt,docx,xlsx');
		$adapter->addValidator('Size', false, (100 * 1024 * 1024));
		$adapter->addValidator('Count', false, 1);
		
		// 上传文件重命名
		$fileinfo = $adapter->getFileInfo();
		$ext = $this->getExtension($fileinfo);
		$rename = date('YmdHis').rand(0,9).rand(0,9).rand(0,9).'.'.$ext;
		$adapter->addFilter('Rename', array('target' => $rename, 'overwrite' => true));
		
		if (!$adapter->receive())
		{
			return $adapter->getMessages();
		}
		
		return true;
	}
	
	protected function getExtension($files)
	{
		$file = '';
		
		if(!empty($files))
		{
			foreach($files as $val)
				$file = $val['name'];
			
			$exts = @split("[/\\.]", $file);
			$n = count($exts) - 1;
			$exts = $exts[$n];
			
			return $exts;
		}
	}
}